<?php
/**
 * Created by PhpStorm.
 * User: YanZ
 * Date: 15/11/11
 * Time: 下午8:25
 */

namespace Home\Controller;


use Home\Common\Response;
use Think\Controller\RestController;

class CartController extends RestController
{
    private $user;

    public function _initialize()
    {
        $this->user = session('user');
        if (!$this->user) {
            $response = new Response();
            $response->setFailState('UN_LOGIN');
            $this->response($response, 'json');
            exit;
        }
    }

    //创建商品
    public function addProduct()
    {
        $response = new Response();
        $pid = I("product_id");
        $did = I("district");
        $discountId = I('product_discount_id');
        if($discountId == "0"){
          $discountId = NULL;
        }
        $uid = $this->user['user_id'];

        if (empty($discountId) || $discountId == NULL) {
            $isSale = 0;
        } else {
            $isSale = 1;
        }

        //创建商品
        $dao = M("shopping_cart");
        $isExistGood = $dao->where('user_id = %d and product_id = %d and (( %d = 0 and product_discount_id = 0) or ( %d = 1 and product_discount_id = %d))', $uid, $pid, $isSale, $isSale, $discountId)->setInc("num", 1) > 0;
        // var_dump($dao);
        //没有商品创建商品
        if (!$isExistGood) {
            $data = array(
                'product_id' => $pid,
                'district_id' => $did,
                'product_discount_id' => $discountId,
                'user_id' => $uid,
                'num' => 1
            );
            M("shopping_cart")->add($data);
        }

//        $Dao = D('Product');
//        $result = $Dao
//            ->join('product_template on product.product_template_id = product_template.product_template_id')
//            ->join('product_discount on product_discount.product_id = product.product_id')
//            ->where('product.product_id = %d and product.status = "0"', I('product_id'))->find();
//
//        $response->addData('product', $result);

        $this->response($response, 'json');
    }

    //删除所有商品
    public function removeGood()
    {
        $response = new Response();
        $user_id = $this->user['user_id'];
        $cart_id = I("cart_id");
        M("shopping_cart")->where("user_id = %d and shopping_cart_id = %d", $user_id, $cart_id)->delete();
        $this->response($response, 'json');
    }

    public function getCount()
    {
        $response = new Response();
        $user_id = $this->user['user_id'];
        $Dao = M("shopping_cart");

        $result = $Dao->field('sum(num) as count')->where("user_id = %d", $user_id)->find();

        $response->addData('count', $result['count']);
        $this->response($response, 'json');
    }

    //获取所有商品
    public function getProducts()
    {
        $response = new Response();
        $user_id = $this->user['user_id'];
        $Dao = M("shopping_cart");

        $products = $Dao->field('*, shopping_cart.product_id as product_id, product_class.name as class_name, product.name as name')
            ->join('product on product.product_id = shopping_cart.product_id')
            ->join('product_template on product.product_template_id = product_template.product_template_id')
            ->join('product_class on product_template.class3 = product_class.product_class_id')
            ->join('LEFT JOIN product_discount on shopping_cart.product_discount_id = product_discount.product_discount_id')
            ->where("user_id = %d", $user_id)->select();

        $result = array();
        foreach ($products as &$product) {
            $class3 = $product['class3'];
            $class_name = $product['class_name'];
            $sendtype = $product['sendtype'];
            if (!is_array($result[$class3 . '_' . $sendtype])) {
                $result[$class3 . '_' . $sendtype] = array('class_name' => $class_name, 'sendtype' => $sendtype);
                $result[$class3 . '_' . $sendtype]['products'] = array();
            }

            array_push($result[$class3 . '_' . $sendtype]['products'], $product);
        }

        $activity = M('shopping_cart_activity')->where('status = 1')->select();
        if(count($activity)){
          $response->addData('activity', $activity[0]);
        }
        $response->addData("result", $result);
        // var_dump($Dao);
        $this->response($response, 'json');
    }

    //更新商品数量
    public function updateProduct()
    {
        $response = new Response();
        $num = I("num");

        $user_id = $this->user['user_id'];
        if ($num == "0" || $num == 0) {
            M("shopping_cart")->where("shopping_cart_id=%d and user_id = %d", I("shopping_cart_id"), $user_id)->delete();
        } else {
            $dao = M("shopping_cart");
            $shopping_product = $dao->where("shopping_cart_id= %d and user_id = %d", I("shopping_cart_id"), $user_id)->find();
            $product_discount_id = $shopping_product['product_discount_id'];
            $product_id = $shopping_product['product_id'];
            //判断是否为促销商品
            if($product_discount_id> 0){
              //查询促销商品剩余量，product_discount表中，remain_amount字段
              $remain_amount = M('product_discount')->field('remain_amount')->where('product_discount_id = %d', $product_discount_id)->find()['remain_amount'];
              //剩余量不足则返回提示，反之，则更新购物车数量
              $this->checkBeforeUpdate($remain_amount, $num, $response, $dao);
            }else{  //非促销商品，查询商品剩余量
                //查询促销商品剩余量，product表中，default_amount字段
                $remain_amount = M('product')->field('default_amount')->find($product_id)['default_amount'];
                //库存不足，返回并提示，反之，更新购物车
                $this->checkBeforeUpdate($remain_amount, $num, $response, $dao);
            }
        }

        $this->response($response, 'json');
    }

    //更新购物车前先检查数量
    public function checkBeforeUpdate($remain_amount, $num, $response, $dao){
      if($remain_amount < $num){
          $response->addData("num", $remain_amount);
      } else{
          $dao->where('shopping_cart_id = %d', I("shopping_cart_id"))->setField('num', $num);
      }
    }

}
